﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Entities;
using Business;
using DevComponents.DotNetBar;
namespace Presentation
{
    public partial class frmQuanLySach : DevComponents.DotNetBar.Office2007Form
    {
        
        DataTable dt = new DataTable();
        DataView dv = new DataView();
        public frmQuanLySach()
        {
            InitializeComponent();
            dgvSach.AutoGenerateColumns = false;
            
            DataGridViewTextBoxColumn colMaSach = new DataGridViewTextBoxColumn();
            colMaSach.Name = "MaSach";
            colMaSach.DataPropertyName = "MaSach";
            colMaSach.Width = 50;
            colMaSach.HeaderText = "Mã sách";

            DataGridViewTextBoxColumn colTenSach = new DataGridViewTextBoxColumn();
            colTenSach.Name = "TenSach";
            colTenSach.DataPropertyName = "TenSach";
            colTenSach.HeaderText = "Tên sách";
            colTenSach.Width = 200;

            DataTable dtTheLoai = TheLoaiService.GetTheLoaiTable();
            DataGridViewComboBoxColumn colTheLoai = new DataGridViewComboBoxColumn();
            colTheLoai.Name = "MaTheLoai";
            colTheLoai.DataSource = dtTheLoai;
            colTheLoai.DisplayMember = "TenTheLoai";
            colTheLoai.ValueMember = "MaTheLoai";
            colTheLoai.DataPropertyName = "MaTheLoai";
            colTheLoai.HeaderText = "Thể loại";
            colTheLoai.AutoComplete = true;

            //
            DataTable dtTacGia = TacGiaService.GetTacGiaDataTable();
            DataGridViewComboBoxColumn colTacGia = new DataGridViewComboBoxColumn();
            colTacGia.Name = "MaTacGia";
            colTacGia.DataSource = dtTacGia;
            colTacGia.DisplayMember = "TenTacGia";
            colTacGia.ValueMember = "MaTacGia";
            colTacGia.DataPropertyName = "MaTacGia";
            colTacGia.HeaderText = "Tác giả";
            //colTacGia.AutoComplete = true;
            


            DataGridViewTextBoxColumn colSoLuong = new DataGridViewTextBoxColumn();
            colSoLuong.Name = "SoLuong";
            colSoLuong.DataPropertyName = "SoLuong";
            colSoLuong.HeaderText = "Số lượng tồn";

            DataGridViewTextBoxColumn colDonGia = new DataGridViewTextBoxColumn();
            colDonGia.Name = "DonGia";
            colDonGia.DataPropertyName = "DonGia";
            colDonGia.HeaderText = "Đơn giá";

            dgvSach.Columns.Add(colMaSach);
            dgvSach.Columns.Add(colTenSach);
            dgvSach.Columns.Add(colTheLoai);
            dgvSach.Columns.Add(colTacGia);
            dgvSach.Columns.Add(colSoLuong);
            dgvSach.Columns.Add(colDonGia);
            
        }

        private void frmQuanLySach_Load(object sender, EventArgs e)
        {
            LoadGridView();
        }
        void LoadGridView()
        {
            dt = SachService.GetSachTable();
            //bs.DataSource = dt;
            //bdnav.BindingSource = bs;
            dt.TableName = "Sach";
            dt.AcceptChanges();
            dv.Table = dt;
            dgvSach.DataSource = dt;

            
        }

        private void btnThoat_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        
        private void dgvSach_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            if (e.Control.GetType() == typeof(DataGridViewComboBoxEditingControl))
            {
                DataGridViewComboBoxEditingControl cb = e.Control as DataGridViewComboBoxEditingControl;
                cb.DropDownStyle = ComboBoxStyle.DropDown;
                cb.AutoCompleteSource = AutoCompleteSource.ListItems;
                cb.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
                
                cb.SelectedIndex = -1;
            }
        }

        private void dgvSach_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            MessageBoxEx.Show("Nhập liệu không đúng!", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
            
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {

            LoadGridView();
        }

        private void dgvSach_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
        {
            int maSach=int.Parse(e.Row.Cells["MaSach"].FormattedValue.ToString());
            if (!SachService.CheckDelete(maSach))
            {
                MessageBoxEx.Show("Không thể xóa sách này!", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                e.Cancel = true;
            }
            else if(maSach>SachService.GetCurrentID())
            {
                for (int i = e.Row.Index+1; i < dgvSach.RowCount; i++)
                {
                    dgvSach["MaSach", i].Value = maSach++;
                }
                
            }
        }

        private void dgvSach_UserAddedRow(object sender, DataGridViewRowEventArgs e)
        {
            int id = GetID();
            for (int i = e.Row.Index - 1; i < dgvSach.RowCount; i++)
            {
                dgvSach["MaSach", i].Value = id++;
            }
        }

        private int GetID()
        {
            dv.RowStateFilter = DataViewRowState.Added;
            DataTable dtThem = dv.ToTable();

            int id = -1;
            if (dtThem.Rows.Count == 0)
            {
                id = SachService.GetCurrentID();

            }
            else
            {
                id = (int)dtThem.Rows[dtThem.Rows.Count - 1]["MaSach"];

            }
            return id + 1;
        }

        private bool RowValidate(int rowIndex)
        {
            if (rowIndex == dgvSach.Rows.Count-1)
                return true;
            DataGridViewRow row = dgvSach.Rows[rowIndex];
            if (row.Cells["TenSach"].FormattedValue.ToString() == "")
            {
                MessageBox.Show(row.Cells["TenSach"].Value.ToString());
                return false;
            }
            if (row.Cells[2].FormattedValue.ToString() == "")
            {
                MessageBox.Show("Tác giả");
                return false;
            }
            //if (row.Cells["MaTacGia"].FormattedValue.ToString() == "")
            //{
            //    MessageBox.Show("asd");
            //    return false;
            //}
            if (row.Cells["SoLuong"].FormattedValue.ToString() == "")
            {
                MessageBox.Show("số lượng");
                return false;
            }
            if (row.Cells["DonGia"].FormattedValue.ToString() == "")
            {
                MessageBox.Show("Đon giá");
                return false;
            }

            return true;
        }

        private void dgvSach_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
        {
            if (e.RowIndex < dgvSach.RowCount-1)
            {
                for (int i = 0; i < dgvSach.Columns.Count; i++)
                {
                    if (dgvSach[i,e.RowIndex].Value.ToString() == "")
                    {
                        MessageBox.Show("Không được bỏ trống");
                        dgvSach.CurrentCell = dgvSach[i, e.RowIndex];
                        dgvSach.BeginEdit(true);
                        e.Cancel = true;
                        return;
                    }
                }
            }
        }

        private void btnCapNhat_Click(object sender, EventArgs e)
        {
            CapNhat();
        }

        private void dgvSach_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            if (e.RowIndex == dgvSach.Rows.Count - 1)
                return;
            DataGridViewCell cell = dgvSach[e.ColumnIndex, e.RowIndex];

            if (e.FormattedValue.ToString() == "")
            {

                MessageBoxEx.Show("Nhập liệu không đúng!", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                cell.Style.BackColor = Color.Red;
                cell.Style.ForeColor = Color.White;

                dgvSach.CurrentCell = cell;
                dgvSach.BeginEdit(true);
                e.Cancel = true;
                return;

            }

            if (dgvSach.Columns[e.ColumnIndex].Name == "SoLuong" || dgvSach.Columns[e.ColumnIndex].Name == "DonGia")
            {
                double x = -1;
                if (!double.TryParse(e.FormattedValue.ToString(), out x) || x <= 0)
                {
                    MessageBoxEx.Show("Nhập liệu không đúng!", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    cell.Style.BackColor = Color.Red;
                    cell.Style.ForeColor = Color.White;
                    dgvSach.CurrentCell = cell;
                    dgvSach.BeginEdit(true);

                    e.Cancel = true;
                    return;
                }

            }


            cell.Style.BackColor = Color.White;
            cell.Style.ForeColor = Color.Black;
        }

        private bool CapNhat()
        {
            dv.RowStateFilter = DataViewRowState.Added;
            DataTable dtThem = dv.ToTable();

            dv.RowStateFilter = DataViewRowState.ModifiedCurrent;
            DataTable dtCapNhat = dv.ToTable();

            dv.RowStateFilter = DataViewRowState.Deleted;
            DataTable dtXoa = dv.ToTable();
            bool kq = false;
            //for (int i = 0; i < dtCapNhat.Rows.Count; i++)
            //{
            //    for (int j = 0; j < dtCapNhat.Columns.Count; j++)
            //    {
            //        if (dtCapNhat.Rows[i][j] == null)
            //        {
            //            return false;
            //        }
            //    }
            //}

            //for (int i = 0; i < dtThem.Rows.Count; i++)
            //{
            //    for (int j = 0; j < dtThem.Columns.Count; j++)
            //    {
            //        if (dtThem.Rows[i][j].ToString() == "")
            //        {
            //            return false;
            //        }
            //    }
            //}
            for (int i = 0; i < dtThem.Rows.Count; i++)
            {
                SachDTO s = new SachDTO();
                s.TenSach =(string) dtThem.Rows[i]["TenSach"];
                s.MaTacGia = (int)dtThem.Rows[i]["MaTacGia"];
                s.MaTheLoai = (int)dtThem.Rows[i]["MaTheLoai"];
                s.DonGia = (double)dtThem.Rows[i]["DonGia"];
                s.SoLuong = (int)dtThem.Rows[i]["SoLuong"];
                s.TinhTrang = 1;
                SachService.Insert(s);
                kq = true;
            }
            for (int i = 0; i < dtXoa.Rows.Count; i++)
            {
                int maSach = (int)dtXoa.Rows[i]["MaSach"];
                SachService.SetDelete(maSach);//Set trạng thái sách ==0 --> sách bị xóa tạm
                kq = true;
            }

            for (int i = 0; i < dtCapNhat.Rows.Count; i++)
            {
                SachDTO s = new SachDTO();

                s.MaSach=(int)dtCapNhat.Rows[i]["MaSach"];
                s.TenSach = (string)dtCapNhat.Rows[i]["TenSach"];
                s.MaTacGia = (int)dtCapNhat.Rows[i]["MaTacGia"];
                
                s.MaTheLoai = (int)dtCapNhat.Rows[i]["MaTheLoai"];
                s.DonGia = (double)dtCapNhat.Rows[i]["DonGia"];
                s.SoLuong = (int)dtCapNhat.Rows[i]["SoLuong"];
                s.TinhTrang = 1;
                SachService.Update(s);
                kq = true;
            }
            
            dv.RowStateFilter = DataViewRowState.CurrentRows;
            if (kq)
            {
                MessageBoxEx.Show("Đã cập nhật!", "Thông báo!", MessageBoxButtons.OK, MessageBoxIcon.Information);

            }
            else
            {
                MessageBoxEx.Show("Không thể cập nhật!", "Thông báo!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            return kq;
        }

        private void KiemTraDong(int index)
        {
            for (int i = 0; i < dgvSach.ColumnCount; i++)
            {
                if (dgvSach[i, index].FormattedValue.ToString() == "")
                {
                    dgvSach.CurrentCell = dgvSach[i, index];
                    dgvSach.BeginEdit(true);
                    MessageBox.Show("Sai");
                    break;
                }
            }
        }

        private void dgvSach_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            
        }

        private void bindingNavigatorMoveLastItem_Click(object sender, EventArgs e)
        {

        }

        private void bindingNavigatorMoveNextItem_Click(object sender, EventArgs e)
        {
            dgvSach.Rows[1].Selected = true;
            
        }

        private void frmQuanLySach_FormClosing(object sender, FormClosingEventArgs e)
        {
            DataTable table = dt.GetChanges();
            if (table!=null && table.Rows.Count > 0)
            {
                DialogResult r = MessageBoxEx.Show("Bạn có muốn lưu lại các thông tin?", "Thông báo!", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
                if (r == DialogResult.Cancel)
                {
                    e.Cancel = true;

                }
                else if (r == DialogResult.Yes)
                {
                    if (!CapNhat())
                        e.Cancel = true;
                }
            }
        }

        private void dgvSach_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void btnDelete_Click(object sender, EventArgs e)
        {

        }
    }
}
